package com.buobao.controller.management;

import com.buobao.entity.Book;
import com.buobao.service.BookService;
import com.buobao.service.exception.BussinessException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/management/book")
public class MBookController {
    @Resource
    private BookService bookService;

    @GetMapping("/index.html")
    public ModelAndView showBook() {
        return new ModelAndView("/management/book");
    }


    @PostMapping("/upload")
    @ResponseBody
    public Map upload(@RequestParam("img")MultipartFile file, HttpServletRequest request) throws IOException {
        URL resource = request.getServletContext().getResource("/"); //获取应用根目录
        String path = resource.getPath() + "upload/";
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        file.transferTo(new File(path+fileName+suffix)); //保存文件到本地
        Map result = new HashMap();
        //返回的格式按照wangeditor要求组织
        result.put("errno",0);
        result.put("data",new String[]{"/upload/"+fileName+suffix});
        return result;
    }

    @PostMapping("/create")
    @ResponseBody
    public Map create(Book book){
        Map result = new HashMap();
        try {
            book.setEvaluationQuantity(0);
            book.setEvaluationScore(0f);
            Document parse = Jsoup.parse(book.getDescription());
            Element img = parse.select("img").first();
            String src = img.attr("src");
            book.setCover(src);
            bookService.insert(book);
            result.put("code","0");
            result.put("msg","success");
        } catch (BussinessException e) {
            e.printStackTrace();
            result.put("code",e.getCode());
            result.put("msg",e.getMsg());
        }
        return result;
    }
}
